package com.yjt.javatest.filter;

import com.yjt.javatest.dao.UserMapper;
import com.yjt.javatest.entity.LoginUser;
import com.yjt.javatest.entity.User;
import com.yjt.javatest.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.rmi.RemoteException;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {


    @Resource
    UserMapper userMapper;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //解析token
        String userid;
        Claims claims = JwtUtil.parseJWT(token);
        userid = claims.getSubject();
        User user = userMapper.selectById(userid);
        if(user == null) {
            throw new RemoteException("token失效");
        }
        LoginUser loginUser = new LoginUser(user, user.getType().getName());
        //存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        JwtUtil.refreshToken(token, response);
        //放行
        filterChain.doFilter(request, response);
    }
}
